package cn.com.headfree.generalquery.controller;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.generalquery.vo.GeneralManageQueryVo;
import cn.com.headfree.generalquery.service.GeneralManageQueryService;
import cn.com.headfree.util.ExcelExportUtil;
import cn.com.headfree.util.GeneralManageQueryExportExcelUtil;
import cn.com.headfree.util.GetFullDeptByErpNoUtil;
import cn.com.headfree.util.SysDictionaryUtil;
import com.gta.edu.sdk.common.dto.Page;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping(value = "/generalManageQuery", produces = "application/json;charset=UTF-8")
public class GeneralQueryController extends ExBaseController {

    private static final Logger LOG = LogManager.getLogger(GeneralQueryController.class);

    //导出excel表头
    @Value("${general_manage_query_title}")
    private String generalManageQueryTitle;

    @Resource
    private GeneralManageQueryService generalManageQueryService;


    @RequestMapping("/findPersonGeneralInfoListByCondition")
    @ResponseBody
    public ResultData findPersonGeneralInfoListByCondition(HttpServletRequest request,Page<GeneralManageQueryVo> page, GeneralManageQueryVo generalManageQueryVo){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if(user == null || user.getRemark() == null){
            result.setErrorMsg("获取当前登录人失败");
            result.setSuccess(false);
        }else{
            if(user.getRemark().equals("2") || user.getRemark().equals("1")){//管理员/普通人员看到本单位
                generalManageQueryVo.setOrgId(user.getBaseOrgId());
            }
        }
        try{
            generalManageQueryService.findPersonGeneralInfoListByCondition(page,generalManageQueryVo);
            if(page.getResult() != null && page.getResult().size() > 0){
                solveData(page.getResult());
            }
            result.setSuccess(true);
            result.setData(page);
        }catch (Exception e){
            result.setSuccess(false);
            result.setErrorMsg("查询失败");
            e.printStackTrace();
        }
        return result;
    }

//    @GetMapping("/expertPersonGeneralInfoListByCondition")
//    @GetMapping("/exportExcelInfoList")
    @RequestMapping("/exportExcelInfoList")
    public void exportPersonGeneralInfoList(HttpServletRequest request, HttpServletResponse response,GeneralManageQueryVo generalManageQueryVo){
        User user = this.getLoginUserInfo(request);
        generalManageQueryVo.setOrgId(user.getBaseOrgId());
        try{
            List<GeneralManageQueryVo> list = generalManageQueryService.exportPersonGeneralInfoListByCondition(generalManageQueryVo);
            if(list != null && list.size() > 0){
                solveData(list);
            }
            //获取标题
            String[] generalManageQueryTitles = generalManageQueryTitle.split(",");
            String sheetName = "数据导出";
            //组装数据
            LOG.info("开始组装数据");
            String[][] Content = GeneralManageQueryExportExcelUtil.makeData(list, generalManageQueryTitles);
            //创建workbook
            XSSFWorkbook workbook = new XSSFWorkbook();
            LOG.info("开始填充数据");
            workbook = GeneralManageQueryExportExcelUtil.fillDataToExcel(workbook, generalManageQueryTitles, Content, sheetName);//填充数据
            //响应生成excel
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            LOG.info("开始导出excel");
            exportExcel2Browser(request,response, sheetName + sdf.format(new Date()), workbook);
            LOG.info("导出excel成功");
        }catch (Exception e){
            LOG.error("导出失败");
            e.printStackTrace();
        }
    }

    /**
     * 向页面导出excel
     *
     * @param response
     * @param fileName 文件名称
     * @param workbook 工作簿
     */
    private void exportExcel2Browser(HttpServletRequest request, HttpServletResponse response, String fileName, XSSFWorkbook workbook) {
        OutputStream os = null;
        try {
            GeneralManageQueryExportExcelUtil.setResponseHeader(request, response, fileName);
            os = response.getOutputStream();
            workbook.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void solveData(List<GeneralManageQueryVo> list){
        Map<String,Object> map = GetFullDeptByErpNoUtil.getOrgDeptList();
        for(GeneralManageQueryVo vo:list){
            vo.setEducationName(SysDictionaryUtil.getNameByValueForDefault("PersonnelQualifications",vo.getEducationName()));
            vo.setQualifilevelname(SysDictionaryUtil.getNameByValueForDefault("QualificationLevel",vo.getQualifilevelname()));
            vo.setEmpTitleName(SysDictionaryUtil.getNameByValueForDefault("TalentTitle",vo.getEmpTitleName()));
            vo.setSubjlevelname(SysDictionaryUtil.getNameByValueForDefault("ProfessionalQualifications",vo.getSubjlevelname()));
            vo.setDeptName(GetFullDeptByErpNoUtil.getFullDept(map,vo.getErpNo()));//获取部门全路径
        }
    }



}
